package cn.edu.buaa.purain.rest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServlet;


public abstract class PurainServletFactory {

	private Map<String, HttpServlet> realPathMap = null;
	private Map<String, HttpServlet> regexMap = null;
	
	
	protected PurainServletFactory() {
		realPathMap = new HashMap<String, HttpServlet>();
		regexMap = new HashMap<String, HttpServlet>();
	}
	
	//protected abstract void parser(String xmlPath);
	
	public HttpServlet getServlet(String uriPath) {
		Set<String> set = realPathMap.keySet();
		if (set.contains(uriPath)) {              //real path matched
			return realPathMap.get(uriPath);
		}
		
		set = regexMap.keySet();
		for (String s : set) {                    //regex matched
			if (PurainUrlHelper.match(s, uriPath)) {
				return regexMap.get(s);
			}
		}
		
		return null;
	}
	
	
	public void put(String path, HttpServlet servlet) throws UrlConflictException {
		if (PurainUrlHelper.isRegexPath(path)) {
			if (regexMap.keySet().contains(path)) {
				throw new UrlConflictException("Url Conflicted");
			}
			regexMap.put(PurainUrlHelper.urlPath2RegexPath(path), servlet);
		}else {
			if (realPathMap.keySet().contains(path)) {
				throw new UrlConflictException("Url Conflicted");
			}
			realPathMap.put(path, servlet);
		}
	}
	
	/*public void dump() {
		for(Map.Entry<String, HttpServlet> entry : realPathMap.entrySet()){
        	System.out.println(entry.getValue() + ":" + entry.getKey());
        }
		
		for(Map.Entry<String, HttpServlet> entry : regexMap.entrySet()){
        	System.out.println(entry.getValue() + ":" + entry.getKey());
        }
	}*/
	
	public Map<String, HttpServlet> getRealPathMap() {
		return realPathMap;
	}

	public void setRealPathMap(Map<String, HttpServlet> realPathMap) {
		this.realPathMap = realPathMap;
	}

	public Map<String, HttpServlet> getRegexMap() {
		return regexMap;
	}

	public void setRegexMap(Map<String, HttpServlet> regexMap) {
		this.regexMap = regexMap;
	}
}
